<template>
  <div>
    <el-card>
      <el-row>
        <el-form :inline="true">
          <el-form-item label="审批状态" prop="approveStatus">
            <el-select clearable v-model="search.approveStatus">
              <el-option v-for="item in approveStatusSelect" :key="item.value" :label="item.text" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="流程状态" prop="workflowStatus">
            <el-select clearable v-model="search.workflowStatus">
              <el-option v-for="item in workflowStatusSelect" :key="item.value" :label="item.text"
                :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="待审批">
            <el-switch v-model="search.isSelfPending" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :icon="Search" @click="query()">查询</el-button>
          </el-form-item>
        </el-form>
      </el-row>
      <el-row>
        <el-button type="primary" :icon="Plus" @click="toCreate()">新增</el-button>
      </el-row>
      <el-row>
        <el-table :data="tableList" :border="true" :table-layout="'auto'"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }">
          <el-table-column prop="bussinessName" label="请假" width="180" />
          <el-table-column prop="days" label="天数" width="180" />
          <el-table-column prop="approveStatusText" label="审批状态" />
          <el-table-column prop="workflowStatusText" label="流程状态" />
          <el-table-column prop="submitNickName" label="提交人" />
          <el-table-column prop="submitTime" label="提交时间" />
          <el-table-column label="操作">
            <template #default="scope">
              <el-button v-if="scope.row.isEditForm" type="primary" :icon="EditPen" @click="toUpdate(scope.row)">
                修改
              </el-button>
              <el-button v-if="scope.row.isEditForm" type="primary" :icon="Position" @click="toSubmit(scope.row)">
                提交
              </el-button>
              <el-button v-if="scope.row.approveText" type="primary" :icon="CircleCheck" @click="toApprove(scope.row)">
                {{ scope.row.approveText }}
              </el-button>
              <el-popconfirm title="确定要取消流程吗?" v-if="!scope.row.approveText && scope.row.approvedCount === 0"
                @confirm="toCancel(scope.row)">
                <template #reference>
                  <el-button type="primary" :plain="true">取消</el-button>
                </template>
              </el-popconfirm>
              <el-popconfirm title="确定要删除这条数据?" v-if="scope.row.isEditForm" @confirm="toDelete(scope.row)">
                <template #reference>
                  <el-button type="danger" :icon="Delete">删除</el-button>
                </template>
              </el-popconfirm>
              <div class="more" v-if="scope.row.approveStatus !== WorkflowStatusEnum.NotStarted">
                <el-dropdown trigger="click">
                  <el-button plain>
                    更多
                    <el-icon class="el-icon--right"><arrow-down /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <div>
                        <el-dropdown-item @click="toTimeLine(scope.row.id)">
                          <el-text type="primary">审批记录</el-text>
                        </el-dropdown-item>
                      </div>
                      <div>
                        <el-dropdown-item @click="toFlowChart(scope.row)">
                          <el-text type="primary">流程图</el-text>
                        </el-dropdown-item>
                      </div>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-row>

      <Pagination :total="search.total" v-model:pageIndex="search.pageIndex" v-model:pageSize="search.pageSize"
        @change="query()"></Pagination>
    </el-card>

    <el-dialog v-model="dialogVisible" @close="closeDialog()" :close-on-click-modal="false" title="表单" width="400">
      <el-form :label-width="'auto'" ref="ruleFormRef" :model="formData" :rules="rules">
        <el-row>
          <el-col :span="24">
            <el-form-item label="名称" prop="roleName">
              <el-input placeholder="名称" v-model="formData.bussinessName" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="天数" prop="days">
              <el-input placeholder="天数" v-model="formData.days" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="isSubmit">
          <el-col :span="24">
            <el-form-item label="选择流程" prop="workflowName">
              <el-select v-model="formData.workflowName">
                <el-option v-for="item in flowNameSelect" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <div v-if="formData.workflowStatus === WorkflowStatusEnum.InProgress">
          <el-row>
            <el-col :span="24">
              <el-form-item label="是否通过" prop="action">
                <el-radio-group v-model="approveInfo.action">
                  <el-radio value="Agree">同意</el-radio>
                  <el-radio value="Refuse">拒绝</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="审批备注" prop="remark">
                <el-input placeholder="审批备注" v-model="approveInfo.remark" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog()">取消</el-button>
          <el-button v-if="isSave" type="primary" @click="save()">保存</el-button>
          <el-button v-if="isSubmit" type="primary" @click="sumbit(ruleFormRef)" :loading="loading">提交</el-button>
          <el-button v-if="formData.workflowStatus === WorkflowStatusEnum.InProgress" type="primary" @click="approve()">
            审批
          </el-button>
        </div>
      </template>
    </el-dialog>

    <el-drawer v-model="drawer" title="审批记录" direction="rtl">
      <el-timeline style="max-width: 300px">
        <el-timeline-item v-for="(activity, index) in activities" :key="index" :icon="activity.icon"
          :color="lineColor(activity.action)" :size="activity.size" :timestamp="activity.time">
          <div>
            <div>{{ activity.message }}</div>
            <div style="color: #909399">{{ activity.remark }}</div>
          </div>
        </el-timeline-item>
      </el-timeline>
    </el-drawer>

    <FlowChart v-if="flowChartVisible" v-model="flowChartVisible" :workflowInstanceId="workflowInstanceId" />
  </div>
</template>

<script lang="ts" setup>
import {
  Plus,
  Delete,
  EditPen,
  Search,
  Position,
  View,
  CircleCheck,
} from "@element-plus/icons-vue";
import WorkflowExampleApi, {
  WorkflowExampleModel,
  WorkflowExampleQuery,
  WorkflowExampleEdit,
  BaseApproveInfo,
  EnumData,
} from "@/api/workflow/example";
import successMsg from "@/utils/successMsg";
import { ApproveActionEnum, WorkflowStatusEnum } from "@/enums/WorkflowEnum";
import { EditEnum } from "@/enums/EditEnum";
import { FormInstance, FormRules } from "element-plus";

const tableList = ref<WorkflowExampleModel[]>();

//查询条件
const search = reactive<WorkflowExampleQuery>({
  searchString: "",
  isSelfPending: false,
  total: 0,
  pageIndex: 1, //第几页
  pageSize: 10, //每页多少条
});

onMounted(async () => {
  await querySelect();
  await query();
});

const approveStatusSelect = ref<EnumData[]>();
const workflowStatusSelect = ref<EnumData[]>();
const flowNameSelect = ref();
const querySelect = async () => {
  approveStatusSelect.value = await WorkflowExampleApi.getApproveStatusSelect();
  workflowStatusSelect.value = await WorkflowExampleApi.getWorkflowStatusSelect();
  flowNameSelect.value = await WorkflowExampleApi.queryFlowNameSelect();
};

const query = async () => {
  const { dataList, totalCount } = await WorkflowExampleApi.query(search);
  search.total = totalCount;
  tableList.value = dataList;
};

const formEdit = ref<WorkflowExampleEdit>({});
const editType = ref<EditEnum>();
const isSave = ref(false);
const toCreate = () => {
  dialogVisible.value = true;
  editType.value = EditEnum.create;
  isSave.value = true;
  formData.value = {};
  formEdit.value = {};
};

const toUpdate = (row: WorkflowExampleModel) => {
  dialogVisible.value = true;
  editType.value = EditEnum.update;
  isSave.value = true;
  formData.value = { ...row };
  formEdit.value = { ...row };
};

const flowChartVisible = ref(false);
const workflowInstanceId = ref();
const toFlowChart = (row: WorkflowExampleModel) => {
  flowChartVisible.value = true;
  workflowInstanceId.value = row.workflowInstanceId;
}

const dialogVisible = ref(false);
const save = async () => {
  formEdit.value = formData.value;
  const { success, message } = await WorkflowExampleApi[EditEnum[editType.value]](formEdit.value);
  successMsg(success, message, async () => {
    dialogVisible.value = false;
    await query();
  });
};

const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules<WorkflowExampleModel>>({
  workflowName: [{ required: true, message: "请选择流程", trigger: "change" }],
});

const loading = ref(false);
const sumbit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  loading.value = true;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      const { success, message } = await WorkflowExampleApi.submit(
        formData.value.id,
        formData.value.workflowName
      );
      successMsg(success, message, async () => {
        loading.value = false;
        dialogVisible.value = false;
        await query();
      });
    }
  });
};

const approveInfo = ref<BaseApproveInfo>({
  action: ApproveActionEnum.Agree,
  remark: "",
});
const approve = async () => {
  const { success, message } = await WorkflowExampleApi.approve(approveInfo.value);
  successMsg(success, message, async () => {
    dialogVisible.value = false;
    await query();
  });
};

const toCancel = async (row: WorkflowExampleModel) => {
  const { success, message } = await WorkflowExampleApi.cancel(row.id);
  successMsg(success, message, await query());
};

const toDelete = async (row: WorkflowExampleModel) => {
  const { success, message } = await WorkflowExampleApi.delete(row.id);
  successMsg(success, message, await query());
};

const formData = ref<WorkflowExampleModel>({});
const isSubmit = ref(false);
const toApprove = (row: WorkflowExampleModel) => {
  dialogVisible.value = true;
  formData.value = { ...row };
  approveInfo.value.id = row.id;
};

const toSubmit = (row: WorkflowExampleModel) => {
  isSubmit.value = true;
  dialogVisible.value = true;
  formData.value = { ...row };
};

const closeDialog = () => {
  isSubmit.value = false;
  isSave.value = false;
  dialogVisible.value = false;
};

const drawer = ref(false);
const activities = ref();
const toTimeLine = async (id: string) => {
  drawer.value = true;
  activities.value = await WorkflowExampleApi.getTimeLine(id);
};

const lineColor = (action: string) => {
  switch (action) {
    case "_start":
      return "#409EFF";
    case "_finish":
      return "#67C23A";
    default:
      return "#E6A23C";
  }
};
</script>

<style scoped lang="scss">
.el-select {
  --el-select-width: 120px;
}

.more {
  display: inline;
}

button+.more {
  margin: 0 12px;
}
</style>
